package com.example.smartcity_ikun3.ui.person.activity

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import com.example.smartcity_ikun3.R
import com.example.smartcity_ikun3.logic.model.LoginModel
import com.example.smartcity_ikun3.logic.network.RetrofitService.Companion.create
import com.example.smartcity_ikun3.logic.network.SmartApi
import com.example.smartcity_ikun3.logic.util.Util.show
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class NewPasswordActivity : AppCompatActivity() {

    private lateinit var mPassword: EditText
    private lateinit var mNewPassword: EditText
    private lateinit var mBtnOk: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        setContentView(R.layout.activity_new_password)
        title = "修改密码"
        mPassword = findViewById(R.id.Password)
        mNewPassword = findViewById(R.id.NewsPassword)
        mBtnOk = findViewById(R.id.newBtnOk)


        // 点击修改密码
        mBtnOk.setOnClickListener {
            if (mPassword.text.isEmpty() && mNewPassword.text.isEmpty()){
                "原密码或新密码不能为空".show()
            }else{
                getSharedPreferences("token", Context.MODE_PRIVATE).apply {
                    val token = getString("token", "").toString()
                    create<SmartApi>().newPassword(token, RequestBody.create("application/json".toMediaTypeOrNull(), JSONObject().apply {
                        put("oldPassword", mPassword.text.toString())
                        put("newPassword", mNewPassword.text.toString())
                    }.toString())).enqueue(object : Callback<LoginModel>{
                        override fun onFailure(p0: Call<LoginModel>, p1: Throwable) {
                            "修改成功".show()
                            Log.d("NET", "onFailure: PassWord --> ${p1.message}")
                        }

                        override fun onResponse(p0: Call<LoginModel>, p1: Response<LoginModel>) {
                            val body = p1.body()
                            if (body != null){
                                if (body.code == 200){
                                    "修改成功".show()
                                }else body.msg.show()
                            }
                        }
                    })
                }
            }
        }

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        finish()
        return super.onOptionsItemSelected(item)
    }
}